package com.mfl.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mfl.common.PageResult;
import com.mfl.context.BaseContext;
import com.mfl.mapper.RemarkMapper;
import com.mfl.mapper.UserMapper;
import com.mfl.pojo.dto.RemarkDTO;
import com.mfl.pojo.dto.RemarkPageQueryDTO;
import com.mfl.pojo.dto.RemarkQueryUserNameDTO;
import com.mfl.pojo.entity.Remark;
import com.mfl.pojo.entity.User;
import com.mfl.pojo.vo.RemarkPageQueryVO;
import com.mfl.pojo.vo.RemarkQueryUserNameVO;
import com.mfl.service.RemarkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class RemarkServiceImpl implements RemarkService {

    @Autowired
    private RemarkMapper remarkMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 新增评论
     * @param remarkDTO
     */
    @Override
    public void insert(RemarkDTO remarkDTO) {
        Remark remark = Remark.builder()
                .type(remarkDTO.getType())
                .courseId(remarkDTO.getCourseId())
                .userId(BaseContext.getCurrentId())
                .content(remarkDTO.getContent())
                .createTime(LocalDateTime.now())
                .build();
        remarkMapper.insert(remark);
    }

    /**
     * 分页查询评论
     * @param remarkPageQueryDTO
     */
    @Override
    public PageResult pageQuery(RemarkPageQueryDTO remarkPageQueryDTO) {
        PageHelper.startPage(remarkPageQueryDTO.getPage(), remarkPageQueryDTO.getPageSize());
        Page<RemarkPageQueryVO> page = remarkMapper.pageQuery(remarkPageQueryDTO);
        page.getResult().forEach(item -> {
            User user = userMapper.getById(item.getUserId());
            item.setUserName(user.getName());
            item.setAvatar(user.getAvatar());
        });
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 批量删除评论
     * @param ids
     */
    @Override
    public void batchDelete(List<Integer> ids) {
        remarkMapper.deleteByIds(ids);
    }

    @Override
    public List<RemarkQueryUserNameVO> queryUserName(RemarkQueryUserNameDTO remarkQueryUserNameDTO) {
        return remarkMapper.queryUserName(remarkQueryUserNameDTO);
    }
}
